package com.allwees.bs.module.mms.mq.listener;

import com.allwees.bs.module.mms.dao.SupplierApplyDao;
import com.allwees.bs.module.mms.dao.SupplierDao;
import com.allwees.bs.module.mms.entity.Supplier;
import com.allwees.bs.module.mms.entity.SupplierApply;
import com.allwees.eladmin.bs.service.BranchUserService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;

@Component
@RabbitListener(queues = "q.Merchant.SupplierApplyApproved")
public class SupplierApplySuccessListener {

    @Autowired
    private SupplierApplyDao supplierApplyDao;

    @Autowired
    private SupplierDao supplierDao;

    @Autowired
    private BranchUserService branchUserService;

    @RabbitHandler
    @Transactional
    public void onEvent(String applyUuid) {
        createSupplierApply(applyUuid);
    }

    private boolean createSupplierApply(String applyUuid) {

        SupplierApply apply = supplierApplyDao.findByUuid(applyUuid);
        if (apply == null) {
            return false;
        }

        Supplier supplier = apply.toSupplier();
        supplier.setDeptId(0L);
        supplierDao.insert(supplier);

        //supplier的流程已废弃
//        MerchantDeptCreateBo bo = new MerchantDeptCreateBo();
//        bo.setBranchType(EBranchType.SUPPLIER);
//        bo.setBranchUuid(supplier.getUuid());
//        bo.setDeptName(apply.getCompanyName());
//        bo.setPid(1L);
//
//        bo.setEmail(apply.getEmail());
//        bo.setPhone(apply.getPhone());
//        bo.setNickname(apply.getUsername());
//        UserDto user = branchUserService.createMerchantUser(bo);

//        Supplier supplierUpdate = new Supplier();
//        supplierUpdate.setDeptId(Optional.ofNullable(user.getDeptId()).orElse(null));
//        supplierDao.updateByUuid(supplierUpdate, supplier.getUuid());

        return true;
    }
}
